#include					"UdpServer.h"
#include					"RotatingBuffer.h"
UdpServer::UdpServer(Processor & proc) : _proc(proc), _current_msg(0)
{
	_buffer = new RotatingBuffer(40096);
	_buffer->init();
	_server.bind(4243);
	connect(&_server, SIGNAL(readyRead()), this, SLOT(handle_read()));
	//_socket.push_back(new QtAsyncUdpSocket(_proc));
	//_socket.front()->connectToHost("10.23.99.185", "4242");
	//_socket.front()->connectToHost("127.0.0.1", "4242");
}

UdpServer::~UdpServer()
{

}

void						UdpServer::disconnect(unsigned int id)
{
	for (std::list<QtAsyncUdpSocket*>::iterator it = _socket.begin(); it != _socket.end();)
	{
		delete *it;
		it = _socket.erase(it);
	}
}

void						UdpServer::connectToClient(std::string ip, std::string port)
{
	QtAsyncUdpSocket		*socket = new QtAsyncUdpSocket(_proc);
	_socket.push_back(socket);
	socket->connectToHost(ip, port);
}

void						UdpServer::handle_read()
{
	int						received = 0;

	while (_server.hasPendingDatagrams()) 
	  {
         QHostAddress sender;
         quint16 senderPort;
		 received = _server.readDatagram((char*)_tmp_buf, 4096, &sender, &senderPort);
		if (received > 0)
			 onReceive(received);
     }
}

void						UdpServer::onReceive(int bytes_transferred)
{
	for (int cnt = 0; cnt < bytes_transferred; ++cnt)
		_buffer->write(_tmp_buf[cnt]);
	if (!_current_msg && _buffer->size() >= 2)
		getOrderSize();
	while (_buffer->size() >= _current_msg && _current_msg > 0)
	{
		size_t size = _buffer->size();
		std::vector<byte>		*harvest = new std::vector<byte>;
		for (unsigned short cnt = 0; cnt < _current_msg; ++cnt)
			harvest->push_back(_buffer->read());
		_proc(harvest, 0);
		_current_msg = 0;
		if (_buffer->size() >= 2)
			getOrderSize();
	}
}

void						UdpServer::getOrderSize()
{
	byte size[2];
	size[0] = _buffer->read();
	size[1] = _buffer->read();
	_current_msg = *((unsigned short*) size);
}

void						UdpServer::sendToAll(IOrder* order)
{
	std::list<QtAsyncUdpSocket*>::iterator it = _socket.begin();

	while (it != _socket.end())
	{
		(*it)->sendOrder(order);
		it++;
	}
}
